<!-- filename: frontend/src/components/CategoryDetails/ArtistList.vue -->
<template>
  <view class="artist-list-container">
    <view v-if="isLoading" class="loading-state">加载中...</view>
    <view v-else-if="!listData || listData.length === 0" class="empty-state">
      暂无歌手数据
    </view>
    
    <scroll-view 
      class="list-scroll-view" 
      :scroll-y="true"
      :scroll-top="scrollTop"
      :scroll-with-animation="true"
    >
      <view v-for="group in listData" :key="group.key">
        <view :id="`group-${group.key}`" class="group-title">{{ group.key }}</view>
        <view 
          v-for="item in group.items" 
          :key="item" 
          class="list-item" 
          @click="handleItemClick(item)"
        >
          {{ item }}
        </view>
      </view>
    </scroll-view>
    
    <view class="index-nav">
       <view 
        v-for="group in listData" 
        :key="group.key" 
        class="index-nav-item"
        @click="scrollTo(group.key)"
       >
        {{ group.key }}
       </view>
    </view>
  </view>
</template>

<script setup>
import { getCurrentInstance, onMounted, ref, watch } from "vue";

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
const props = defineProps({
  role: { type: String, default: "" },
});
const emit = defineEmits(["item-click"]);

const listData = ref([]);
const isLoading = ref(true);
const scrollTop = ref(0);
const groupTitleTops = ref({});
const instance = getCurrentInstance();

watch(
  () => props.role,
  (newRole, oldRole) => {
    if (newRole !== oldRole) {
      isLoading.value = true;
      listData.value = [];
      fetchArtists();
    }
  }
);


const fetchArtists = () => {
  let apiUrl = `${API_BASE_URL}/api/artists`;
  if (props.role === "cover") {
    apiUrl += "?role=翻唱";
  }

  console.log("Fetching artists from URL:", apiUrl); // Log the URL being requested

  uni.request({
    url: apiUrl,
    success: (res) => {
      console.log("API Response Status:", res.statusCode); // Log the status code
      console.log("API Response Data:", res.data); // Log the response data

      if (res.statusCode === 200 && Array.isArray(res.data)) {
        listData.value = res.data;
        if (listData.value.length > 0) {
          calculateGroupTops();
        }
      } else {
        // Handle cases where status is 200 but data is not an array or is empty
        uni.showToast({ title: `加载失败: ${res.statusCode}`, icon: "error" });
      }
    },
    fail: (err) => {
      console.error("API Request Failed:", err); // Log the error
      uni.showToast({ title: "加载失败", icon: "error" });
    },
    complete: () => {
      isLoading.value = false;
    },
  });
};

const calculateGroupTops = () => {
  instance.proxy.$nextTick(() => {
    groupTitleTops.value = {};
    const query = uni.createSelectorQuery().in(instance);
    query
      .selectAll(".group-title")
      .boundingClientRect((data) => {
        if (data) {
          data.forEach((item) => {
            const key = item.id.split("-")[1];
            groupTitleTops.value[key] = item.top;
          });
        }
      })
      .exec();
  });
};

const handleItemClick = (itemName) => {
  emit("item-click", itemName);
};

const scrollTo = (key) => {
  const targetTop = groupTitleTops.value[key];
  if (targetTop !== undefined) {
    scrollTop.value = targetTop + 0.1;
    instance.proxy.$nextTick(() => {
      scrollTop.value = targetTop;
    });
  }
};

onMounted(() => {
  fetchArtists();
});
</script>

<style scoped>
.artist-list-container {
  width: 100%;
  height: 100%;
  display: flex;
  position: relative;
}
.loading-state, .empty-state {
  width: 100%;
  text-align: center;
  padding-top: 50px;
  color: #888;
}
.list-scroll-view {
  flex: 1;
  height: 100%;
}
.list-group {
  margin-bottom: 10px;
}
.group-title {
  background-color: #f4f4f4;
  padding: 5px 15px;
  font-size: 14px;
  color: #666;
  font-weight: bold;
}
.list-item {
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
  font-size: 16px;
  cursor: pointer;
}
.list-item:hover {
  background-color: #f9f9f9;
}
.index-nav {
    position: absolute;
    right: 5px;
    top: 50%;
    transform: translateY(-50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: rgba(0, 0, 0, 0.1);
    border-radius: 10px;
    padding: 5px 0;
}
.index-nav-item {
    padding: 2px 5px;
    font-size: 12px;
    color: #333;
    cursor: pointer;
}
</style>
